<template>
  <div class="register">
    <!-- 删除 -->
      <div class="close">
        <i class="iconfont iconicon-test"></i>
      </div>
      <!-- logo -->
      <div class="logo">
        <i class="iconfont iconnew"></i>
      </div>
      <!-- 用户名 -->
      <div class="username">
        <hm-input err-msg='请输入正确的手机号' :rules="userRule" v-model='username' placeholder='请输入用户名(手机号)'></hm-input>
      </div>
      <!-- 昵称 -->
      <div class="nickname">
        <hm-input err-msg='昵称必须是2-6位 的中文' :rules="nicknameRule" v-model=' nickname' placeholder='请输入昵称'></hm-input>
      </div>
      <!-- 密码 -->
      <div class="password">
        <hm-input err-msg='请输入正确的密码' :rules="passRule" v-model='password' type='password' placeholder='请输入密码'></hm-input>
      </div>
      <!-- 注册 -->
      <div class="register-btn">
        <hm-button @click='register'>注册</hm-button>
      </div>
      <!-- 跳转到登录 -->
      <div class="go-login">
        没有账号? 立即 <router-link to="/login" >登录</router-link>
      </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      username: '',
      password: '',
      nickname: '',
      userRule: /^1\d{4,10}$/,
      passRule: /^\w{3,12}$/,
      nicknameRule: /^[\u4e00-\u9fa5]{2,6}$/
    }
  },

  methods: {
    async register () {
      // 先校验用户的输入
      if (!this.userRule.test(this.username)) {
        this.$toast('请输入正确的账号/手机号')
        return
      }
      if (!this.passRule.test(this.password)) {
        this.$toast('请输入正确的昵称')
        return
      }
      if (!this.nicknameRule.test(this.nickname)) {
        this.$toast('请输入正确的密码')
        return
      }
      // 使用 axios 发送请求
      const res = await this.$axios.post('/register', {
        username: this.username,
        password: this.password,
        nickname: this.nickname
      })
      // console.log(res)
      const { statusCode, message } = res.data
      if (statusCode === 200) {
        // 注册成功
        // 添加用户提示
        this.$toast.success(message)

        // 跳转到登录页
        // this.$router.push('/login')
        // (命名路由)
        this.$router.push({
          name: 'login',
          params: {
            username: this.username,
            password: this.password
          }
        })
      } else {
        this.$toast.fail(message)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
  .register {
  padding: 20px;
  .close {
    i {
      font-size: 27px;
    }
  }
  .logo {
    text-align: center;
    i {
      font-size: 126px;
      color: #d81e06;
    }
  }
    .go-login {
    text-align: center;
    margin-top: 30px;
    a {
      color: #d81e06;
    }
  }
  }
</style>
